package com.ruoyi.system.domain;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public  class LoginItem {
    String userName;
    int failcount = 0;
    Date lastTryTime;

    public static final int BLOCK_TIME = 300;
    public static Map<String, LoginItem> loginFailUsers = new HashMap<String, LoginItem>();
    public static final int TRY_TIMES = 5;

    public boolean isBlock() {

        if (failcount >= TRY_TIMES) {
            long timeSpan = (new Date().getTime() - lastTryTime.getTime()) / 1000;
            //5分钟内
            System.out.println(timeSpan);
            if (timeSpan <= BLOCK_TIME) {
                return true;
            } else {
                loginFailUsers.remove(userName);
            }

        }
        return false;
    }

    public LoginItem(String userName, int failcount, Date lastTryTime) {
        this.userName = userName;
        this.failcount = failcount;
        this.lastTryTime = lastTryTime;
    }

    public void addTryTimes() {
        failcount++;
        lastTryTime = new Date();
    }

    /**
     * 错误次数太多，暂时屏蔽
     *
     * @param userName
     */
    public static boolean isBlockLogin(String userName) {
        if (userName != null) {
            LoginItem item = loginFailUsers.get(userName);
            if (item != null) {
                if (item.isBlock()) {
                    item.lastTryTime = new Date();
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 增加登录错误次数
     *
     * @param userName
     */
    public static void addFailCount(String userName) {
        if (userName != null) {
            LoginItem item = loginFailUsers.get(userName);
            if (item == null) {
                loginFailUsers.put(userName, new LoginItem(userName, 1, new Date()));
            } else {
                item.addTryTimes();
            }
        }
    }


}
